import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    children:[
      {
        path: '/test',
        name: 'test',
        component: () => import('../views/Test.vue')
      },
         {
        path: '/list',
        name: 'list',
        component: () => import('../views/exam/list.vue')
      },
        {
        path: '/product',
        name: 'product',
        component: () => import('../views/exam/product.vue')
      },
      {
        path: '/search',
        name: 'search',
        component: () => import('../views/search/search.vue')
      },

         {
        path: '/error',
        name: 'error',
        component: () => import('../views/exam/error.vue')
      },


    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

router.beforeEach((to, from, next) => {
  //to 到哪里
  //from 从哪来
  /* 必须调用 `next` */
  //alert(from.path + '-->' + to.path);
  if(to.path === '/login'){
    sessionStorage.removeItem("userId");
    sessionStorage.removeItem("userName");
    sessionStorage.removeItem("token");
    next();
  }else if(to.path === '/logout'){
    sessionStorage.removeItem("userId");
    sessionStorage.removeItem("username");
    sessionStorage.removeItem("token");
    next({path: '/login'})
  }else{
    let token = sessionStorage.getItem("token");
    if(token == null){
      next({path: '/login'})
    }else{
      next();
    }
  }
})